<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>06_列表渲染_过滤与排序</title>
  </head>
  <body>
    <!--
1. 列表过滤
2. 列表排序
-->
    <div id="app">
      <input type="text" v-model="studentName" />
      <ul>
        <li v-for="(student,index) in getStudents" :key="index">
          {{`${student.id+'--'+student.name+'--'+student.age}`}}
        </li>
      </ul>
      <button @click=" orderType = 'asc'">年龄升序</button>
      <button @click=" orderType = 'desc'">年龄降序</button>
      <button @click=" orderType = 'default'">原本排序</button>
    </div>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
      new Vue({
        el: '#app',
        data: {
          studentName: '',
          orderType: 'default',
          students: [
            { id: 1, name: '张三', age: 21 },
            { id: 2, name: '李四', age: 20 },
            { id: 3, name: '王五', age: 24 },
            { id: 4, name: '赵六', age: 18 },
            { id: 5, name: '小健', age: 20 },
            { id: 6, name: '小华', age: 24 },
            { id: 7, name: '小静', age: 15 },
          ],
        },
        computed: {
          getStudents() {
            let { studentName, orderType, students } = this

            //过滤
            const searchStudents = students.filter((stu) => {
              return stu.name.indexOf(studentName) !== -1
            })

            //默认排序
            if (orderType === 'default') {
              return searchStudents
            }
            //升序降序
            searchStudents.sort((a, b) => {
              console.log(a.age, b.age)
              return orderType === 'asc' ? a.age - b.age : b.age - a.age
            })
            return searchStudents
          },
        },
      })
    </script>
  </body>
</html>
